package com.swift.violent.mainstay.core.base.core.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.swift.violent.mainstay.common.constants.Global;
import com.swift.violent.mainstay.common.lang.CommonResultOutput;
import com.swift.violent.mainstay.common.util.SecurityUtil;
import com.swift.violent.mainstay.core.base.core.modal.bo.ApiUserEntity;
import com.swift.violent.mainstay.core.base.core.service.ApiUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 接口管理者信息表 前端控制器
 *
 * @author xuhaifeng
 * @since 2021 -01-23
 */
@RestController
@RequestMapping("/base/api/user")
@SuppressWarnings({"unused", "FieldCanBeLocal", "SpringJavaAutowiredFieldsWarningInspection"})
public class ApiUserController {
    @Autowired
    private ApiUserService userService;

    /**
     * 新增api管理者用户接口
     * Insert api user object.
     *
     * @param userEntity the user entity
     *
     * @return the object
     */
    @PostMapping(value = "/insertApiUser")
    public Object insertApiUser(@RequestBody @Valid ApiUserEntity userEntity) {
        final QueryWrapper<com.swift.violent.mainstay.core.base.core.modal.po.ApiUserEntity> queryWrapperUser = new QueryWrapper<>();
        queryWrapperUser.eq(com.swift.violent.mainstay.core.base.core.modal.po.ApiUserEntity.ACCOUNT, userEntity.getAccount());
        if (userService.count(queryWrapperUser) == Integer.parseInt(Global.NUM_0)) {
            final com.swift.violent.mainstay.core.base.core.modal.po.ApiUserEntity apiUserEntity = JSON.parseObject(JSON.toJSONString(userEntity),
                    com.swift.violent.mainstay.core.base.core.modal.po.ApiUserEntity.class);
            userService.save(apiUserEntity.setSecretKey(SecurityUtil.encryptPassword(apiUserEntity.getSecretKey())));
            return CommonResultOutput.commonSuccessOutput();
        }
        throw new RuntimeException("管理用户已存在，不可再次添加");
    }

}